package com.qf.utils;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 公用常量
 * @Data: 2022/8/31 16:05
 * @Pacakge: com.qf.utils
 * @ClassName: ConnectionUtils
 * @Author: fan
 */
public class ConnectionUtils {
    //绑定线程
    ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    //获取数据源
    DataSource dataSource;
    //通过set注入数据源
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    //获取数据连接对象
    public Connection getConnection() {
        try {
            //通过线程获取数据库连接对象
            Connection connection = threadLocal.get();
            //判断
            if (connection == null){
                //从数据库中获取连接对象
                connection = dataSource.getConnection();
                //将其存储到线程中
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将当前数据库连接对象解绑
     */
    public void removeConnection(){
        threadLocal.remove();
    }
}
